﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace WoChu.CF.BaseFrame.Util
{
    /// <summary>
    /// ConfigSeting 应该程序配置文件处理相关。
    /// </summary>
    public class ConfigSetting
    {
        private static readonly string PARENT_SETTING_NODE = "/configuration/appSettings";
        private static readonly string NODES_PATH = "/configuration/appSettings/add";
        private static readonly string APP_CONFIG_FILE = ".config";

        private ConfigSetting()
        {
        }


        #region 设置配置文件相关...
        /// <summary>
        /// 设置配置文件中值（每一个配置的信息都以这样的方式(key = " + pKeyName +" ,value =)）
        /// </summary>
        /// <param name="pKeyName">得到的键值的名称</param>
        /// <param name="pKeyValue">要设置的键值</param>
        public static void SetKeyValue(string pKeyName, string pKeyValue)
        {
            SetKeyValue(pKeyName, pKeyValue, null, null);
        }
        /// <summary>
        /// 设置配置文件中值（每一个配置的信息都以这样的方式(key = " + pKeyName +" ,value =)）
        /// </summary>
        /// <param name="pKeyName">得到的键值的名称</param>
        /// <param name="pKeyValue"> 要设置的键值</param>
        /// <param name="pFullPathName">配置文件完整的路径</param>
        public static void SetKeyValue(string pKeyName, string pKeyValue, string pFullPathName)
        {
            SetKeyValue(pKeyName, pKeyValue, pFullPathName, null);
        }
        /// <summary>
        /// 设置配置文件中值（每一个配置的信息都以这样的方式(key = " + pKeyName +" ,value =)）
        /// </summary>
        /// <param name="pKeyName">得到的键值的名称</param>
        /// <param name="pKeyValue"></param>
        /// <param name="pFullPathName">配置文件完整的路径</param>
        /// <param name="pNodesPath">Node在XML配置文件的路径></param>
        public static void SetKeyValue(string pKeyName, string pKeyValue, string pFullPathName, string pNodesPath)
        {
            string nodePath = NODES_PATH;
            if (pNodesPath != null && pNodesPath != "")
            {
                nodePath = pNodesPath;
            }
            XmlDocument XMLDoc;
            XMLDoc = new XmlDocument();
            string pathName = "";
            if (pFullPathName != null && pFullPathName != "")
            {
                pathName = pFullPathName;
            }
            else
            {
                //通过它也可以得到 AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
                //通过try catch 判断应该程序是windows form 还是web 应用程序 
                pathName = (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName)) + APP_CONFIG_FILE;
            }
            bool b = System.IO.File.Exists(pathName);
            if (!b)
            {
                TraceEx.Write("配置文件" + pathName + "不存在!", SysMessageLevel.SysFileInfo);
                return;
            }

            XMLDoc.Load(pathName);

            XmlNodeList nodes = XMLDoc.SelectNodes(nodePath);
            bool findKey = false;
            foreach (XmlNode node in nodes)
            {
                if (node.Attributes["key"].Value.ToLower() == pKeyName.ToLower())
                {
                    node.Attributes["value"].Value = pKeyValue;
                    findKey = true;
                    break;
                }
            }
            if (!findKey)
            {
                XmlNode parentNode = XMLDoc.SelectSingleNode(PARENT_SETTING_NODE);

                XmlElement newNode = XMLDoc.CreateElement("add");
                XmlAttribute att = XMLDoc.CreateAttribute("key");
                att.Value = pKeyName;
                newNode.Attributes.Append(att);

                att = XMLDoc.CreateAttribute("value");
                att.Value = pKeyValue;
                newNode.Attributes.Append(att);

                parentNode.AppendChild(newNode);
            }
            XMLDoc.Save(pathName);
        }
        #endregion 设置配置文件相关...

        #region 获取配置文件处理信息相关...
        /// <summary>
        /// 得到配置文件中值（每一个配置的信息都以这样的方式(key = " + pKeyName +" ,value =)）
        /// </summary>
        /// <param name="pKeyName">得到的键值的名称</param>
        /// <returns> 返回 Key对应的值</returns>
        public static string GetKeyValue(string pKeyName)
        {
            return GetKeyValue(pKeyName, null, null);
        }
        /// <summary>
        ///  得到配置文件中值（每一个配置的信息都以这样的方式(key = " + pKeyName +" ,value =)）
        /// </summary>
        /// <param name="pKeyName">得到的键值的名称</param>
        /// <param name="pFullPathName">配置文件完整的路径</param>
        /// <returns>返回 Key对应的值</returns>
        public static string GetKeyValue(string pKeyName, string pFullPathName)
        {
            return GetKeyValue(pKeyName, pFullPathName, null);
        }
        /// <summary>
        ///  得到配置文件中值（每一个配置的信息都以这样的方式(key = " + pKeyName +" ,value =)）
        /// </summary>
        /// <param name="pKeyName">得到的键值的名称</param>
        /// <param name="pFullPathName">配置文件完整的路径</param>
        /// <param name="pNodesPath">Node在XML配置文件的路径</param>
        /// <returns>返回 Key对应的值</returns>
        public static string GetKeyValue(string pKeyName, string pFullPathName, string pNodesPath)
        {
            string nodePath = NODES_PATH;
            if (pNodesPath != null && pNodesPath != "")
            {
                nodePath = pNodesPath;
            }
            XmlDocument XMLDoc;
            XMLDoc = new XmlDocument();
            string pathName = "";

            if (pFullPathName != null && pFullPathName != "")
            {
                pathName = pFullPathName;
            }
            else
            {
                pathName = (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + APP_CONFIG_FILE;
            }
            bool b = System.IO.File.Exists(pathName);
            if (!b)
            {
                TraceEx.Write("配置文件" + pathName + "不存在!", SysMessageLevel.SysFileInfo);
                return null;
            }
            XMLDoc.Load(pathName);
            XmlNodeList nodes = XMLDoc.SelectNodes(nodePath);
            string val = null;
            foreach (XmlNode node in nodes)
            {
                if (node.Attributes["key"].Value.ToLower() == pKeyName.ToLower())
                {
                    val = node.Attributes["value"].Value;
                    break;
                }
            }
            if (val == null || val == "")
            {
                TraceEx.Write("代码执行说明: (key = " + pKeyName + " ,value =)在config文件中没有配置。", SysMessageLevel.CodeRunInfo);
            }
            return val;
        }
        #endregion 获取配置文件处理信息相关...
    }
}
